package com.rpc.core.codec.adapter;

import com.rpc.core.codec.RpcCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;


public class NettyDecodeAdapter extends LengthFieldBasedFrameDecoder {

    private RpcCodec codec;

    public NettyDecodeAdapter(RpcCodec codec) {
        super(1048576, 0, 4, 0, 4);
        this.codec = codec;
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame == null)
            return null;
        return codec.deserialize(frame);
    }

    @Override
    protected ByteBuf extractFrame(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
        return buffer.slice(index, length);
    }


}
